package com.yi.wood.web.ctrl;

import com.yi.wood.entity.User;
import com.yi.wood.service.po.CachePo;
import com.yi.wood.service.po.UserCachePo;
import com.yi.wood.web.ctrl.dto.UserParam;
import com.yi.wood.web.service.UserProService;
import lombok.extern.log4j.Log4j2;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Date;
import java.util.UUID;

/**
 * @author moyi
 * @since 1.0
 */
@Validated
@RestController
@RequestMapping("/api/user")
@Log4j2
public class UserCtrl extends BaseCtrl {

    @Resource
    private UserProService userProService;

    /**
     * 注册用户
     *
     * @return 处理结果
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST, consumes = "application/json")
    public Object register(@RequestBody @Valid UserParam userParam) {
        String userName = userParam.getUserName();
        String password = userParam.getPassword();
        String email = userParam.getEmail();

        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);
        user.setEmail(email);
        user.setLastModifyTime(new Date());
        user.setBirthday(new Date());
        user.setUuid(UUID.randomUUID().toString());
        user = userProService.addData(user);
        user.setPassword("");
        return success(user
        );
    }

    /**
     * 用户登录
     *
     * @param userParam 认证信息
     * @return 用户登录结果
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST, consumes = "application/json")
    public Object login(@RequestBody UserParam userParam) {
        // TODO 验证码
        String userName = userParam.getUserName();
        String password = userParam.getPassword();
        UserCachePo userCachePo = userProService.login(userName, password);
        return success(userCachePo);
    }

    /**
     * 通过token获取用户信息
     *
     * @return 用户信息
     */
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public Object info() {
        CachePo userInfo = getUserByToken();
        return success(userInfo);
    }

    /**
     * 分页查询所有用户信息
     *
     * @return 用户信息
     */
    @RequestMapping(value = "/page", method = RequestMethod.GET)
    public Object list(@RequestParam(required = false) String userName,
                       @RequestParam(required = false) String phone,
                       @RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "10") Integer pageSize) {
        return success(userProService.pageUserInfoList(userName, phone, pageNum, pageSize));
    }
}
